import GameMgr from './GameManager'

const { ccclass, property } = cc._decorator

@ccclass
export default class NewClass extends cc.Component {
  onLoad() {
    this.gameInit()
  }

  gameInit() {
    GameMgr.instance.musicMgr.init()
    GameMgr.instance.musicMgr.playBgm('bgm')
    this.preLoadResources()
  }

  preLoadResources() {
    const progressBar = this.node.getChildByName('bgc_image').getComponentInChildren(cc.ProgressBar)
    const progressLabel = this.node.getChildByName('bgc_image').getComponentInChildren(cc.Label)
    const bar = progressBar.getComponentInChildren(cc.Sprite)
    let resourceBundle = cc.assetManager.bundles.get('resources')
    const resourcePaths = resourceBundle.getDirWithPath('./')
    const maxLen = resourcePaths.length
    let loadCount = 0
    for (let i = 0; i < maxLen; ++i) {
      const path = resourcePaths[i].path
      cc.resources.preload(
        path,
        (completedCount: number, totalCount: number) => {
          console.log('progress:', '资源加载总计：' + completedCount, '资源总数：' + totalCount)
        },
        (err: Error | null) => {
          if (err) {
            return console.error('preload failed: ' + err.message)
          }
          // 加载进度改变
          loadCount++
          bar.fillRange = cc.misc.clamp01(loadCount / maxLen)
          progressLabel.string = `资源加载中，加载进度${loadCount}/${maxLen}`
          if (loadCount >= maxLen) {
            progressLabel.string = '资源加载完成～'
            bar.fillRange = 1
            setTimeout(() => {
              // 切换场景，进入主页面
              cc.director.loadScene('SceneMain')
            }, 1000)
          }
        }
      )
    }
  }

  // update (dt) {}
}
